const path = require('path')
require('dotenv').config({ path: `./.env.${process.env.NODE_ENV}` })
const Koa = require('koa')
const router = require('./router/index.js')
const bodyParser = require('koa-bodyparser')
const errorMiddleware = require('./middleware/errorMiddle.js')
const static = require('koa-static')
const cors = require('koa2-cors')

const RedisUtility = require('./lib/utils/redis')

RedisUtility.client();

const isProduction = process.env.NODE_ENV === 'production'

const app = new Koa()
app.use(errorMiddleware())

!isProduction && app.use(cors())
app.use(bodyParser())

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

app.use(router.routes())
app.use(router.allowedMethods())
const webRoot = path.join(process.cwd(), 'src/static')
app.use(static(webRoot))
app.listen(3000, () => console.log('server is running'))
